package org.jeecg.crud;

import lombok.SneakyThrows;
import org.geotools.geometry.DirectPosition2D;
import org.geotools.referencing.CRS;
import org.opengis.geometry.DirectPosition;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import org.opengis.referencing.operation.MathTransform;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;

public class CoordinateConverter {

    private CoordinateReferenceSystem sourceCRS;
    private CoordinateReferenceSystem targetCRS;
    private MathTransform transform;

    @SneakyThrows
    public CoordinateConverter(String sourceCRS, String targetCRS) {
        this.sourceCRS = CRS.decode(sourceCRS);
        this.targetCRS = CRS.decode(targetCRS);
        this.transform = CRS.findMathTransform(this.sourceCRS, this.targetCRS);
    }

    public static void main(String[] args) {
        String sourceCRS = "EPSG:xxxx"; // 设置源投影坐标系，根据你的数据选择合适的EPSG码
        String targetCRS = "EPSG:4326"; // 设置目标地理坐标系，这里是WGS 84

        CoordinateConverter converter = new CoordinateConverter(sourceCRS, targetCRS);

        String inputFilePath = "input.txt"; // 输入的投影坐标文件路径
        String outputFilePath = "output.txt"; // 输出的地理坐标文件路径

        converter.convertCoordinates(inputFilePath, outputFilePath);
        System.out.println("坐标转换完成，结果已保存到 output.txt");
    }

    @SneakyThrows
    public void convertCoordinates(String inputFilePath, String outputFilePath) {
        try (BufferedReader reader = new BufferedReader(new FileReader(inputFilePath));
             BufferedWriter writer = new BufferedWriter(new FileWriter(outputFilePath))) {
            String line;
            while ((line = reader.readLine()) != null) {
                String[] coordinates = line.split(",");
                if (coordinates.length == 2) {
                    double x = Double.parseDouble(coordinates[0]);
                    double y = Double.parseDouble(coordinates[1]);

                    DirectPosition sourcePos = new DirectPosition2D(sourceCRS, x, y);
                    DirectPosition targetPos = new DirectPosition2D();
                    transform.transform(sourcePos, targetPos);

                    double latitude = targetPos.getOrdinate(1);
                    double longitude = targetPos.getOrdinate(0);

                    writer.write(latitude + "," + longitude);
                    writer.newLine();
                }
            }
        }
    }
}
